package com.kerbores.utils.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author 王贵源
 *
 *         create at 2014年9月23日 上午10:45:17
 * @description 随机字符串生成器
 */
public class StringGener {

	private String pool = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789";
	private char[] charPool = pool.toCharArray();
	private List<Character> characters;

	/**
	 * 传入可用字符池构建
	 * 
	 * @param pool
	 *            常量池
	 */
	public StringGener(String pool) {
		this.pool = pool;
		fill();
	}

	/**
	 * 增量形式传入常量池
	 * 
	 * @param pool
	 *            常量池增量
	 * @param append
	 *            append标识
	 */
	public StringGener(String pool, boolean append) {
		if (append) {
			this.pool += pool;
			fill();
		} else {
			this.pool = pool;
			fill();
		}
	}

	/**
	 * 填充characters
	 */
	private void fill() {
		characters = new ArrayList<Character>();
		for (char c : charPool) {
			characters.add(c);
		}
	}

	/**
	 * 无参构建,默认使用内置池
	 */
	public StringGener() {
		fill();
	}

	/**
	 * 生成一个随机串
	 * 
	 * @param length
	 *            待生成的随机串的长度
	 * @return 随机串
	 */
	public String next(int length) {
		if (length <= 0) {
			throw new RuntimeException("'" + length + "' is not available length! ");
		}
		String target = "";
		Random r = new Random();
		while (target.length() < length) {
			target += charPool[r.nextInt(charPool.length)];
		}
		return target;
	}

	/**
	 * 生成一个随机串
	 * 
	 * @param length
	 *            待生成的随机串的长度
	 * @param unique
	 *            是否允许有重复字符(true为不允许)
	 * @return 随机串
	 */
	public String next(int length, boolean unique) {
		if (unique) {
			if (length <= 0 || length > charPool.length) {
				throw new RuntimeException("'" + length + "' is not available length! ");
			}
			String target = "";
			Random r = new Random();
			fill();
			while (target.length() < length) {
				target += characters.remove(r.nextInt(characters.size()));
			}
			return target;
		}
		return next(length);
	}
}
